using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Antlr.Runtime.Tree;
using Antlr.Runtime;

namespace NeuroSpeech.Imap
{
	public class BaseImapResponse
	{

		public string CommandID { get; set; }

		public string Response = "";

		public List<string> Lines = new List<string>();

		#region public IXTree  Parse(string text)
		public ITree Parse(string text)
		{
			Antlr.Runtime.ANTLRStringStream ins = new ANTLRStringStream(text);
			ImapResponseParserLexer lex = new ImapResponseParserLexer(ins);
			Antlr.Runtime.BufferedTokenStream inlex = new BufferedTokenStream(lex);
			ImapResponseParserParser parser = new ImapResponseParserParser(inlex);

			return (ITree)parser.compileUnit().Tree;
		}
		#endregion

		public virtual void Process(ImapClient client)
		{
			Response = "";
			do
			{

				string line = client.ReadLine();
				Response += line + "\r\n";
				string l = line.ToLower();
				if (l.StartsWith(CommandID))
				{
					if (!l.StartsWith(CommandID + " ok"))
						throw new ImapProtocolException(Response);
					return;
				}
				ProcessLine(line);
			} while (true);
		}

		protected virtual void ProcessLine(string line)
		{
			Lines.Add(line);
		}

		public virtual void PostProcess(ImapClient client) { 
		}

	}
}
